import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:viser_remit/data/controller/home/home_controller.dart';
import 'package:viser_remit/data/controller/send_money/send_money_controller.dart';
import 'package:viser_remit/data/model/home/country_info_model.dart';
import 'package:viser_remit/data/model/kyc/kyc_response_model.dart';
import 'package:viser_remit/data/model/send_money/servicelist_response_model.dart';
import 'package:viser_remit/view/components/buttons/rounded_loading_button.dart';
import 'package:viser_remit/view/components/checkbox/custom_check_box.dart';
import 'package:viser_remit/view/components/custom_drop_down_button_with_text_field.dart';
import 'package:viser_remit/view/components/custom_loader/custom_loader.dart';
import 'package:viser_remit/view/components/custom_radio_button.dart';
import 'package:viser_remit/view/components/form_row.dart';
import 'package:viser_remit/view/screens/auth/kyc/widget/widget/file_item.dart';
import 'package:viser_remit/view/screens/send_money/widget/summery_scetion.dart';

import '../../../core/utils/dimensions.dart';
import '../../../core/utils/my_color.dart';
import '../../../core/utils/my_strings.dart';
import '../../../core/utils/style.dart';
import '../../../core/utils/util.dart';
import '../../../data/model/send_money/send_money_model.dart' as send_money;
import '../../components/app-bar/viser_remit_app_bar.dart';
import '../../components/buttons/rounded_button.dart';
import '../../components/text-form-field/custom_drop_down_button_with_text_field2.dart';
import '../../components/text-form-field/custom_text_field.dart';

class RecipientScreen extends StatelessWidget {
  const RecipientScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<SendMoneyController>(
      builder: (controller) => GetBuilder<HomeController>(
        builder: (homeController) {
          return Scaffold(
            appBar: ViserRemitAppBar(
              title: MyStrings.recipientInformation.tr,
              isElevation: true,
            ),
            body: SingleChildScrollView(
              physics: const BouncingScrollPhysics(),
              padding: const EdgeInsets.symmetric(horizontal: Dimensions.space16, vertical: Dimensions.space15),
              child: Container(
                padding: const EdgeInsetsDirectional.symmetric(horizontal: Dimensions.space15, vertical: Dimensions.space15),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(Dimensions.space10),
                  color: MyColor.getCardBgColor(),
                  boxShadow: MyUtils.getCardShadow(),
                ),
                child: Column(
                  children: [
                    CustomDropDownTextField2(
                      fillColor: MyColor.textFieldColor,
                      labelText: MyStrings.existingRecipient.tr,
                      selectedValue: controller.selectedRecipients,
                      onChanged: (value) {
                        controller.setSelectedRecipients(value);
                      },
                      items: controller.recipientsList.map((send_money.Recipients method) {
                        return DropdownMenuItem<send_money.Recipients>(
                          value: method,
                          child: Text((method.name ?? MyStrings.noName.tr).tr, style: regularDefault.copyWith(color: MyColor.getTextColor())),
                        );
                      }).toList(),
                    ),
                    const SizedBox(
                      height: Dimensions.space16,
                    ),
                    CustomTextField(
                      animatedLabel: true,
                      needOutlineBorder: true,
                      labelText: MyStrings.recipientInformation.tr,
                      controller: controller.recipientController,
                      focusNode: controller.informationFocusNode,
                      textInputType: TextInputType.text,
                      nextFocus: controller.phoneNumberFocusNode,
                      validator: (value) {
                        if (value!.isEmpty) {
                          return MyStrings.enterYourUsername.tr;
                        } else if (value.length < 6) {
                          return MyStrings.kShortUserNameError.tr;
                        } else {
                          return null;
                        }
                      },
                      onChanged: (value) {
                        return;
                      },
                    ),
                    const SizedBox(
                      height: Dimensions.space16,
                    ),
                    Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.end, children: [
                      Container(
                        width: 50,
                        height: 47,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          color: MyColor.textFieldColor,
                          borderRadius: BorderRadius.circular(Dimensions.defaultRadius),
                        ),
                        child: Text(
                          "+${controller.homeController.selectedReceiveCountry.dialCode}",
                          style: regularDefault.copyWith(color: MyColor.getPrimaryColor()),
                        ),
                      ),
                      const SizedBox(width: Dimensions.space5 + 3),
                      Expanded(
                        child: CustomTextField(
                          animatedLabel: true,
                          needOutlineBorder: true,
                          labelText: MyStrings.recipientPhoneNumber.tr,
                          controller: controller.phoneNumberController,
                          focusNode: controller.phoneNumberFocusNode,
                          nextFocus: controller.emailFocusNode,
                          textInputType: TextInputType.phone,
                          inputAction: TextInputAction.next,
                          onChanged: (value) {
                            controller.detectPhoneNumberChange(value);
                            return;
                          },
                        ),
                      )
                    ]),
                    const SizedBox(
                      height: Dimensions.space16,
                    ),
                    CustomTextField(
                      animatedLabel: true,
                      needOutlineBorder: true,
                      labelText: MyStrings.recipientEmail.tr,
                      controller: controller.emailController,
                      focusNode: controller.emailFocusNode,
                      textInputType: TextInputType.text,
                      nextFocus: controller.addressFocusNode,
                      validator: (value) {
                        if (value!.isEmpty) {
                          return MyStrings.enterYourUsername.tr;
                        } else if (value.length < 6) {
                          return MyStrings.kShortUserNameError.tr;
                        } else {
                          return null;
                        }
                      },
                      onChanged: (value) {
                        return;
                      },
                    ),
                    const SizedBox(
                      height: Dimensions.space16,
                    ),
                    CustomTextField(
                      animatedLabel: true,
                      needOutlineBorder: true,
                      // prefixIcon: MyImages.emailSvg,
                      labelText: MyStrings.recipientAddressS.tr,
                      controller: controller.addressController,
                      focusNode: controller.addressFocusNode,
                      textInputType: TextInputType.text,
                      validator: (value) {
                        if (value!.isEmpty) {
                          return MyStrings.enterYourUsername.tr;
                        } else if (value.length < 6) {
                          return MyStrings.kShortUserNameError.tr;
                        } else {
                          return null;
                        }
                      },
                      onChanged: (value) {
                        return;
                      },
                    ),
                    const SizedBox(
                      height: Dimensions.space16,
                    ),
                    CustomDropDownTextField2(
                      labelText: MyStrings.deliveryMethod.tr,
                      selectedValue: homeController.selectedDeliveryMethod,
                      fillColor: MyColor.textFieldColor,
                      onChanged: (value) {
                        homeController.setSelectedDeliveryMethod(value);
                      },
                      items: homeController.deliveryMethodList.map((CountryDeliveryMethods method) {
                        return DropdownMenuItem<CountryDeliveryMethods>(
                          value: method,
                          child: Text((method.deliveryMethod?.name ?? '').tr, style: regularDefault.copyWith(color: MyColor.getTextColor())),
                        );
                      }).toList(),
                    ),
                    const SizedBox(height: Dimensions.space16),
                    homeController.isServiceLoading
                        ? const Center(child: CustomLoader())
                        : Visibility(
                            visible: homeController.serviceList.isNotEmpty && homeController.isAgentSelected == false,
                            child: CustomDropDownTextField2(
                              fillColor: MyColor.textFieldColor,
                              labelText: MyStrings.service.tr,
                              selectedValue: homeController.selectedServices,
                              hintText: homeController.selectedServices.name ?? ''.tr,
                              onChanged: (value) {
                                homeController.setSelectedServiceMethod(value);
                              },
                              items: homeController.serviceList.map((Services method) {
                                return DropdownMenuItem<Services>(
                                  value: method,
                                  child: Text((method.name ?? '').tr, style: regularDefault.copyWith(color: MyColor.getTextColor())),
                                );
                              }).toList(),
                            ),
                          ),
                    homeController.serviceDynamicFormList.isNotEmpty
                        ? const SizedBox(
                            height: Dimensions.space16,
                          )
                        : const SizedBox.shrink(),
                    Visibility(
                     // visible: homeController.serviceDynamicFormList.isNotEmpty && homeController.serviceList.length > 1 && homeController.selectedServices.name != MyStrings.selectOne,
                      // visible: homeController.formList.isNotEmpty,
                      visible: true,
                      child: ListView.builder(
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          scrollDirection: Axis.vertical,
                          itemCount: homeController.serviceDynamicFormList.length,
                          itemBuilder: (ctx, index) {
                            KycFormModel? model = homeController.serviceDynamicFormList[index];
                            print("this is model type ${model.type}");
                            return Padding(
                              padding: const EdgeInsets.all(3),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  model.type == 'text'
                                      ? Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            CustomTextField(
                                                // animatedLabel: true,
                                                isRequired: model.isRequired == 'optional' ? false : true,
                                                hintText: (model.name ?? ''.tr).toString().capitalizeFirst,
                                                needOutlineBorder: true,
                                                labelText: model.name ?? ''.tr,
                                                validator: (value) {
                                                  if (model.isRequired != 'optional ' && value.toString().isEmpty) {
                                                    return '${model.name.toString().tr.capitalizeFirst} ${MyStrings.isRequired.tr}';
                                                  } else {
                                                    return null;
                                                  }
                                                },
                                                onChanged: (value) {
                                                  homeController.changeSelectedValue(value, index);
                                                }),
                                            const SizedBox(height: Dimensions.space10),
                                          ],
                                        )
                                      : model.type == 'textarea'
                                          ? Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: [
                                                CustomTextField(
                                                    isRequired: model.isRequired == 'optional' ? false : true,
                                                    needOutlineBorder: true,
                                                    labelText: model.name ?? '',
                                                    hintText: (model.name ?? '').capitalizeFirst,
                                                    validator: (value) {
                                                      if (model.isRequired != 'optional ' && value.toString().isEmpty) {
                                                        return '${model.name.toString().capitalizeFirst} ${MyStrings.isRequired}';
                                                      } else {
                                                        return null;
                                                      }
                                                    },
                                                    onChanged: (value) {
                                                      homeController.changeSelectedValue(value, index);
                                                    }),
                                                const SizedBox(height: Dimensions.space10),
                                              ],
                                            )
                                          : model.type == 'select'
                                              ? Column(
                                                  crossAxisAlignment: CrossAxisAlignment.start,
                                                  children: [
                                                    FormRow(label: model.name ?? '', isRequired: model.isRequired == 'optional' ? false : true),
                                                    const SizedBox(
                                                      height: Dimensions.textToTextSpace,
                                                    ),
                                                    CustomDropDownWithTextField(
                                                        list: model.options ?? [],
                                                        onChanged: (value) {
                                                          homeController.changeSelectedValue(value, index);
                                                        },
                                                        selectedValue: model.selectedValue),
                                                    const SizedBox(height: Dimensions.space10)
                                                  ],
                                                )
                                              : model.type == 'radio'
                                                  ? Column(
                                                      crossAxisAlignment: CrossAxisAlignment.start,
                                                      children: [
                                                        FormRow(label: model.name ?? '', isRequired: model.isRequired == 'optional' ? false : true),
                                                        CustomRadioButton(
                                                          title: model.name,
                                                          selectedIndex: homeController.serviceDynamicFormList[index].options?.indexOf(model.selectedValue ?? '') ?? 0,
                                                          list: model.options ?? [],
                                                          onChanged: (selectedIndex) {
                                                            homeController.changeSelectedRadioBtnValue(index, selectedIndex);
                                                          },
                                                        ),
                                                      ],
                                                    )
                                                  : model.type == 'checkbox'
                                                      ? Column(
                                                          crossAxisAlignment: CrossAxisAlignment.start,
                                                          children: [
                                                            FormRow(label: model.name ?? '', isRequired: model.isRequired == 'optional' ? false : true),
                                                            CustomCheckBox(
                                                              selectedValue: homeController.serviceDynamicFormList[index].cbSelected,
                                                              list: model.options ?? [],
                                                              onChanged: (value) {
                                                                homeController.changeSelectedCheckBoxValue(index, value);
                                                              },
                                                            ),
                                                          ],
                                                        )
                                                      : model.type == 'file'
                                                          ? Column(
                                                              crossAxisAlignment: CrossAxisAlignment.start,
                                                              children: [FormRow(label: model.name ?? '', isRequired: model.isRequired == 'optional' ? false : true), Padding(padding: const EdgeInsets.symmetric(vertical: Dimensions.textToTextSpace), child: ConfirmWithdrawFileItem(index: index))],
                                                            )
                                                          : const SizedBox(),
                                  const SizedBox(height: Dimensions.space10),
                                ],
                              ),
                            );
                          }),
                    ),
                    const SizedBox(
                      height: Dimensions.space15,
                    ),
                    if (controller.selectedRecipients.id == -1 || controller.isPhoneNumberChanged)
                      Row(
                        children: [
                          SizedBox(
                            width: 25,
                            height: 25,
                            child: Checkbox(
                              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Dimensions.defaultRadius)),
                              activeColor: MyColor.primaryColor,
                              checkColor: MyColor.colorWhite,
                              value: controller.saveRecipientValue,
                              side: MaterialStateBorderSide.resolveWith(
                                (states) => BorderSide(width: 1.0, color: controller.saveRecipientValue ? MyColor.getTextFieldEnableBorder() : MyColor.getTextFieldDisableBorder()),
                              ),
                              onChanged: (bool? value) {
                                controller.updateRecipient();
                              },
                            ),
                          ),
                          const SizedBox(width: Dimensions.space8),
                          Row(
                            children: [
                              Text(MyStrings.saveRecipient.tr, style: regularLarge),
                              const SizedBox(width: Dimensions.space3),
                            ],
                          ),
                        ],
                      ),
                    const SizedBox(height: Dimensions.space16),
                    SummarySection(controller: controller),
                    const SizedBox(
                      height: Dimensions.space32,
                    ),
                    controller.submitLoading
                        ? const RoundedLoadingBtn()
                        : RoundedButton(
                            fontSize: 16,
                            verticalPadding: 15,
                            text: MyStrings.continueText.tr,
                            press: () {
                              controller.gotToNextPage();
                            },
                          ),
                    const SizedBox(height: 30),
                  ],
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}
